﻿/*
 * Copyright (C) 2023 - 2024 lchfj.cn
 * 
 * This file is part of FastestHost.
 * 
 * FastestHost is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * FastestHost is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with FastestHost. If not, see <https://www.gnu.org/licenses/>.
 */

using System.Text;

namespace Cn.Lchfj.FastestHost
{
    internal class HostsFileChange
    {
        private static readonly string HostsFilePath = "C:\\Windows\\System32\\drivers\\etc\\hosts";

        public static async Task ChangeHosts(IReadOnlyList<HostIP> hosts)
        {
            if (hosts is not { Count: > 0 })
                return;

            var lines = await File.ReadAllLinesAsync(HostsFilePath);


            var lastisWhiteLine = false;


            var sb = new StringBuilder();
            foreach (var line in lines)
            {
                // 空行判断，用于删除多个连续的空行
                if (string.IsNullOrWhiteSpace(line))
                {
                    if (!lastisWhiteLine)
                    {
                        lastisWhiteLine = true;
                        sb.AppendLine();
                    }

                    continue;
                }

                // 是本工具添加的IP地址
                if (line.EndsWith(HostIP.Suffix))
                {
                    continue;
                }

                // 是本次要修改的域名
                if (HostIP.TryParse(line, out var hostIp))
                {
                    if (hosts.Any(h => h.Host == hostIp.Host))
                        continue;
                }


                lastisWhiteLine = false;
                sb.AppendLine(line.Trim());
            }

            // 在前面添加一行空行
            if (!lastisWhiteLine)
                sb.AppendLine();

            // 添加要修改的域名
            foreach (var host in hosts)
            {
                sb.AppendLine(host.ToHostsLineString());
            }

            await File.WriteAllTextAsync(HostsFilePath, sb.ToString(), new UTF8Encoding(false));
        }
    }
}
